/*
Copyright 2010-2011 CumulusCloud
http://cumuluscloud.cc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cumulusCloud.knowledge;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import cumulusCloud.common.ManageUser;
import cumulusCloud.common.objects.CloudSession;
import cumulusCloud.common.objects.CloudUser;
import cumulusCloud.tools.Hashing;

public class SessionKnow {
	static private SessionKnow instance;
	static private Logger logger = java.util.logging.Logger.getLogger(SessionKnow.class.getName());
	
	public static SessionKnow getInstance() {
		if (instance == null) instance = new SessionKnow();
		return instance;
	}
	
	private Map<String, CloudSession> sessionsMap = new ConcurrentHashMap<String, CloudSession>();
	
	private SessionKnow() {
	}
	
	public synchronized String createSession(String user, String password) {
		String token = null;
		
		if (ManageUser.isValidCredential(user, password)) {
			token = Hashing.md5(user + Math.random());
			
			logger.info("New token: " + token + " for user: " + user);
			sessionsMap.put(token, new CloudSession(token, ManageUser.getUser(user)));
		}
		
		return token;
	}
	
	public synchronized void deleteSession(String userToken) {
		logger.info("Deleting session: " + userToken);
		sessionsMap.remove(userToken);
	}
	
	public String getCurrentUserToken(HttpServletRequest request) {
		logger.info("Getting the current session token in the cookies");
		Cookie[] cookies = request.getCookies();
		if (cookies == null) return null;
		
		for (Cookie c:cookies) {
			if (c.getName().equals("cloudusertoken")) {
				return c.getValue();
			}
		}
		
		return null;
	}
	
	public CloudUser getSessionUser(String userToken) {
		CloudSession cs = sessionsMap.get(userToken);
		
		// Check if session exists
		if (cs == null) return null;
		
		// Check if user still exists
		if (ManageUser.getUser(cs.user.name) == null) {
			deleteSession(userToken);
			return null;
		}
		
		return new CloudUser(cs.user);
	}
	
}
